<?php
/**
 * Created by PhpStorm.
 * User: 69568
 * Date: 2018/2/5
 * Time: 21:51
 */

namespace App\Http\Controllers\Auth;


use App\ApiResponse;
use App\Helper;
use App\Http\Controllers\Controller;
use App\Models\SmsCode;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Overtrue\EasySms\EasySms;

class SmsCodeController extends Controller
{

    use ApiResponse;

    public function send(Request $request)
    {
        $phone = $request->phone;

        $smsCode = SmsCode::wherePhone($phone)->orderBy('created_at', 'desc')->first();
        if ($smsCode && $smsCode->created_at->diffInMinutes(Carbon::now()) < 3) {
            return $this->message('验证码发送过于频繁', [], 400);
        }
        $code = random_int(100000, 999999);
        $insert = [];
        $insert['code'] = $code;
        $insert['phone'] = $phone;
        $smsCode = SmsCode::create($insert);

        $config = [
            // HTTP 请求的超时时间（秒）
            'timeout' => 5.0,

            // 默认发送配置
            'default' => [
                // 网关调用策略，默认：顺序调用
                'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,

                // 默认可用的发送网关
                'gateways' => [
                    'aliyun',
                ],
            ],
            // 可用的网关配置
            'gateways' => [
                'errorlog' => [
                    'file' => storage_path('log//easy-sms.log'),
                ],

                'aliyun' => [
                    'access_key_id' => env('ALIYUN_APPKEY'),
                    'access_key_secret' => env('ALIYUN_APPSECRET'),
                    'sign_name' => env('SMS_SIGNNAME'),
                ],

            ],
        ];
        if (Helper::isMobile($phone)) {
            $easySms = new EasySms($config);
            $easySms->send($phone, [
                'content' => '您的验证码为: ' . $smsCode->code,
                'template' => env('ALIYUN_TEMPLATEID'),
                'data' => [
                    'code' => $smsCode->code
                ],
            ]);
        }
        return response()->json(['msg' => '发送成功', 'data' => ['code' => $code,'is_mobile'=>Helper::isMobile($phone)]], 200);
    }
}